* This file take 2010 inpatient data and produces variables to capture past health of ED patients in 2011-12 and 2012-13

set more off

use "$sourcedata/ip_2010.dta", clear

* exclusions: remove duplicates (epikey should be unique)
bys epikey: gen z=_n
keep if z==1

* exclusions: remove duplicated episodes (should not have multiple episodes with same epiorder)
*gen admidate_string = mdy(admidate_month, admidate_day, admidate_year)
bys extract admidate_string epiorder: gen x=_n
drop if x>1


* Just keep those who attend A&E - I NEED TO MAKE THIS SOMEWHERE (SOMEWHERE IN THE 'BUILD DATA' FILE?)
*merge m:1 extract_hesid using "/mnt/data_store/secure/hes/AE/workingdata/ae_index_ids.dta"
merge m:1 extract_hesid using "$saveddata/ae_index_ids.dta"
keep if _merge==3
drop _merge

* obtain dates from final episode of each spell (GS: also need to obtain final discharge method from final episode)
foreach var in disdate_day disdate_month disdate_year dismeth {
gen `var'_temp = `var' if spelend=="Y"
egen `var'_f = max(`var'_temp), by(extract admidate_string)
}

replace disdate_year_f=. if disdate_year_f==1600

* length of stay for spell
gen disdate_f = mdy(disdate_month_f, disdate_day_f, disdate_year_f)
gen admidate_f = mdy(admidate_month, admidate_day, admidate_year)
gen spell_los = disdate_f - admidate_f
replace spell_los=. if spell_los<0

preserve
* Create charlson index (some measure of comorbidity) - TURN THIS ON TO CREATE CHARLSON INDEX TO MERGE IN BELOW
charlson, index(10) idvar(extract) diagprfx(fulldiag3_) wtchrl cmorb
save "$saveddata/charl2010.dta", replace
restore
*/

* Count number of emergency admissions
preserve

keep if epiorder==1
gen n_em_admit2010 = 1 if admimeth<20

collapse (sum) n_em_admit2010, by(extract)

* Cap to one admissions per day in a year
replace n_em_admit2010 = 365 if n_em_admit2010>365

save "$saveddata/data_2010visits_aeonly.dta", replace

restore

* Calculate number of days in hospitals
collapse (max) spell_los , by(extract admidate_f)
collapse (sum) spell_los , by(extract)

replace spell_los = 365 if spell_los>365
rename spell_los los2010 
 
save "$saveddata/data_inpat2010_aeonly_jun20.dta", replace

